<template>
  <div class="questions-view">
    <!-- 统一导航栏 -->
    <NavBar @toggle-sidebar="toggleSidebar" />
    
    <div class="questions-container">
      <!-- 侧边栏 -->
      <div class="sidebar" :class="{ collapsed: sidebarCollapsed }">
        <!-- 头部 -->
        <div class="sidebar-header">
          <h1 class="title">试卷生成系统</h1>
          <p class="subtitle">教师端</p>
        </div>

        <!-- 导航 -->
        <div class="nav-menu">
          <button class="nav-item active" @click="gotoResources">发布资源</button>
          <button class="nav-item" @click="generateExam">生成试卷</button>
        </div>

        <!-- 已选择统计 -->
        <div class="selected-stats">
          <div class="stats-card">
            <h3>已选择习题数量</h3>
            <div class="count">{{ selectedQuestions.length }}</div>
          </div>
        </div>
      </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 顶部栏 -->
      <div class="top-bar">
        <h2>习题库</h2>
        <button
          class="generate-btn"
          @click="backToHome"
        >
          返回
        </button>
      </div>

      <!-- 筛选栏 -->
      <div class="filter-bar">
        <div class="filter-group">
          <label>题型：</label>
          <el-select v-model="filters.type" placeholder="全部" @change="filterQuestions">
            <el-option label="全部" :value="''"></el-option>
            <el-option label="选择题" :value="1"></el-option>
            <el-option label="填空题" :value="2"></el-option>
            <el-option label="解答题" :value="3"></el-option>
          </el-select>
        </div>

        <div class="filter-group">
          <label>难度：</label>
          <el-select v-model="filters.difficulty" placeholder="全部" @change="filterQuestions">
            <el-option label="全部" :value="''"></el-option>
            <el-option label="简单" value="简单"></el-option>
            <el-option label="中等" value="中等"></el-option>
            <el-option label="困难" value="困难"></el-option>
          </el-select>
        </div>

        <div class="search-group">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索习题内容..."
            @input="filterQuestions"
          >
            <template #append>
              <el-button @click="filterQuestions">搜索</el-button>
            </template>
          </el-input>
        </div>

        <el-button @click="resetFilters">重置</el-button>
      </div>

      <!-- 题目列表 -->
      <div class="questions-list">
        <div
            v-for="question in filteredQuestions"
            :key="question.questionId"
            class="question-card"
        >
          <!-- 题目头部 -->
          <div class="question-header">
      <span class="type-tag" :class="getTypeClass(question.type)">
        {{ getTypeName(question.type) }}
      </span>
            <span class="difficulty-tag" :class="getDifficultyClass(question.difficulty)">
        {{ getDifficultyName(question.difficulty) }}
      </span>

            <!-- 操作按钮区域 -->
            <div class="question-actions">
              <el-button
                  size="big"
                  :type="isSelected(question.questionId) ? 'success' : 'default'"
                  @click="toggleQuestion(question)"
              >
                {{ isSelected(question.questionId) ? '已选择' : '选择' }}
              </el-button>

              <el-button
                  size="big"
                  type="primary"
                  @click="openEditDialog(question)"
              >修改
              </el-button>

              <el-button
                  size="big"
                  type="danger"
                  @click="handleDelete(question.questionId)"
              >删除
              </el-button>
            </div>
          </div>

          <!-- 题目内容 -->
          <div class="question-content">
            <p class="question-text">{{ question.content }}</p>

            <!-- 选择题选项 -->
            <div v-if="question.type == 1" class="options">
              <div
                  v-for="(text, key) in question.options"
                  :key="key"
                  class="option"
              >
                {{ key }}. {{ text }}
              </div>
            </div>

            <div class="answer">
              <span class="answer-label">答案：</span>
              <span class="answer-text">{{ question.answer }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 弹窗 -->
  <el-dialog
      v-model="editDialogVisible"
      title="修改题目"
      width="600px"
      :close-on-click-modal="false"
  >
    <el-form :model="editForm" label-width="80px">
      <el-form-item label="题目内容">
        <el-input type="textarea" v-model="editForm.content" rows="3" />
      </el-form-item>

      <el-form-item label="题型">
        <el-select v-model="editForm.type" placeholder="请选择题型">
          <el-option label="单选题" :value="1" />
          <el-option label="判断题" :value="2" />
          <el-option label="简答题" :value="3" />
        </el-select>
      </el-form-item>

      <el-form-item label="难度">
        <el-select v-model="editForm.difficulty" placeholder="请选择难度">
          <el-option label="简单" value="简单" />
          <el-option label="中等" value="中等" />
          <el-option label="困难" value="困难" />
        </el-select>
      </el-form-item>

      <!-- 只有选择题显示选项 -->
      <template v-if="editForm.type === 1">
        <el-form-item
            v-for="(text, key) in editForm.options"
            :key="key"
            :label="`选项 ${key}`"
        >
          <el-input v-model="editForm.options[key]" />
        </el-form-item>
      </template>

      <el-form-item label="答案">
        <el-input v-model="editForm.answer" />
      </el-form-item>
    </el-form>

    <!-- 弹窗底部按钮 -->
    <template #footer>
    <span class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="submitEdit">保存修改</el-button>
    </span>
    </template>
  </el-dialog>
    </div>
</template>

<script setup lang="ts">
import {ref, computed, onMounted, reactive} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {
  getAllQuestionsAPI, getQuestionsByCreatorIdAPI, getQuestionByQuestionIdAPI,
  addQuestionAPI, deleteQuestionByIdAPI, updateQuestionAPI, selectQuestionsAPI
} from '@/apis/index.ts'
import type {UpdateQuestionParams} from "@/apis/questionAPI/updateQuestionAPI.ts"
import { useRouter } from 'vue-router'
import type {SelectQuestionsParams} from "@/apis/examAPI/ExamQuestionsAPI.ts"
import NavBar from '@/components/NavBar.vue'
import { useAuth } from '@/composables/useAuth'

// 题目类型定义
interface Question {
  questionId: number
  creatorId: number
  content: string
  options?: Record<string, string>
  answer: string
  type: number | 1 | 2 | 3         // 1: 选择题, 2: 填空题, 3: 解答题
  difficulty: '简单' | '中等' | '困难'
  createdAt?: string
}

const router = useRouter()

// 导航栏状态
const sidebarCollapsed = ref(false)

// 切换侧边栏
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

// 响应式数据
const questions = ref<Question[]>([])
const selectedQuestions = ref<Question[]>([])
const filteredQuestions = ref<Question[]>([])
const searchKeyword = ref('')
interface QuestionFilters {
  type: '' | number      // 空字符串表示“全部”，number 表示 1 | 2 | 3...
  difficulty: '' | '简单' | '中等' | '困难'
}
const filters = ref<QuestionFilters>({
  type: '',
  difficulty: ''
})
const editDialogVisible = ref(false)
const handleCancel = () => {
  editDialogVisible.value = false
  ElMessage.warning('取消修改')
}

// 方法
const getTypeName = (type: number) => {
  const typeNames = {
    1: '选择题',
    2: '填空题',
    3: '解答题'
  }
  return typeNames[type as keyof typeof typeNames] || type
}

const getDifficultyName = (difficulty: string) => {
  const difficultyNames = {
    '简单': '简单',
    '中等': '中等',
    '困难': '困难'
  }
  return difficultyNames[difficulty as keyof typeof difficultyNames] || difficulty
}

const getTypeClass = (type: number) => {
  const typeClasses = {
    1: 'type-choice',
    2: 'type-fill',
    3: 'type-essay'
  }
  return typeClasses[type as keyof typeof typeClasses] || ''
}

const getDifficultyClass = (difficulty: string) => {
  const difficultyClasses = {
    '简单': 'difficulty-easy',
    '中等': 'difficulty-medium',
    '困难': 'difficulty-hard'
  }
  return difficultyClasses[difficulty as keyof typeof difficultyClasses] || ''
}
const backToHome = () => {
  router.push('/teacher-home')
}

//获取题目列表
const fetchQuestions = async () => {
  try {
    const res = await getQuestionsByCreatorIdAPI(Number(localStorage.getItem('id'))||1)
    if (res.code === 200 && res.data?.list) {
      const convertedList = res.data.list.map(item => ({
        questionId: item.questionId,
        creatorId: item.creatorId,
        content: item.content,
        options: item.options as Record<string, string>,
        answer: item.answer,
        type: item.type,
        difficulty: item.difficulty as '简单' | '中等' | '困难',
        createdAt: String(item.createdAt)
      }));

      questions.value = convertedList;
      filteredQuestions.value = convertedList;

    } else {
      ElMessage.error('获取题目列表失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，无法获取题目列表')
  }
}

onMounted(() => {
  fetchQuestions()
})

//修改习题
const editForm = reactive({
  questionId: null as number | null,
  content: '',
  type: 1,
  difficulty: '中等',
  options: {
    A: '',
    B: '',
    C: '',
    D: '',
  },
  answer: ''
})

// 打开编辑弹窗，初始化数据
const openEditDialog = (question: Question) => {
  editForm.questionId = question.questionId
  editForm.content = question.content
  editForm.type = question.type
  editForm.difficulty = question.difficulty
  // 深拷贝选项，防止直接修改原题目对象
  editForm.options = question.options ? { 
    A: question.options.A || '', 
    B: question.options.B || '', 
    C: question.options.C || '', 
    D: question.options.D || '' 
  } : { A: '', B: '', C: '', D: '' }
  editForm.answer = question.answer
  editDialogVisible.value = true
}

// 提交修改
const submitEdit = async () => {
  if (!editForm.questionId) {
    ElMessage.error('题目ID丢失，无法修改')
    return
  }

  const updatedQuestion: UpdateQuestionParams = {
    questionId: editForm.questionId,
    content: editForm.content,
    type: editForm.type,
    difficulty: editForm.difficulty as '简单' | '中等' | '困难',
    options: editForm.type === 1 ? { ...editForm.options } : undefined,
    answer: editForm.answer
  }

  try {
    const res = await updateQuestionAPI(updatedQuestion)
    if (res.code === 200) {
      ElMessage.success('题目修改成功')
      editDialogVisible.value = false
      await fetchQuestions()
    } else {
      ElMessage.error(res.message || '题目修改失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，修改失败')
  }
}


//删除习题
const handleDelete = async (questionId: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该题目吗？', '提示', {
      type: 'warning',
    })
    const res = await deleteQuestionByIdAPI(questionId)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchQuestions()
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    ElMessage.error('删除操作已取消')
  }
}


const isSelected = (questionId: number) => {
  return selectedQuestions.value.some(q => q.questionId === questionId)
}

const toggleQuestion = (question: Question) => {
  const index = selectedQuestions.value.findIndex(q => q.questionId === question.questionId)
  if (index > -1) {
    selectedQuestions.value.splice(index, 1)
    ElMessage.success('题目已移除')
  } else {
    selectedQuestions.value.push(question)
    ElMessage.success('题目已添加到试卷')
  }
}

//筛选题目
const filterQuestions = () => {
  let filtered = [...questions.value]
  
  // 按题型筛选
  if (filters.value.type) {
    filtered = filtered.filter(q => q.type === filters.value.type)
  }
  
  // 按难度筛选
  if (filters.value.difficulty) {
    filtered = filtered.filter(q => q.difficulty === filters.value.difficulty)
  }
  
  // 按关键词搜索
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(q => 
      q.content.toLowerCase().includes(keyword) ||
      q.answer.toLowerCase().includes(keyword)
    )
  }
  
  filteredQuestions.value = filtered
}

const resetFilters = () => {
  filters.value = {
    type: '',
    difficulty: ''
  }
  searchKeyword.value = ''
  filterQuestions()
}

const generateExam = async () => {
  if (selectedQuestions.value.length === 0) {
    ElMessage.warning('请先选择题目');
    return;
  }

  const questionIds = selectedQuestions.value.map(q => q.questionId);

  try {
    const params: SelectQuestionsParams = {
      examId: Number(localStorage.getItem('examId')||1),
      questionIds,
    };

    const res = await selectQuestionsAPI(params);

    if (res.code === 200) {
      ElMessage.success(`成功关联 ${questionIds.length} 道题目到考试！`);
    } else {
      ElMessage.error(`题目关联失败：${res.message}`);
    }
  } catch (error) {
    console.error(error);
    ElMessage.error('关联题目失败，请稍后重试');
  }
};

const gotoResources = () => {
  router.push('/resources')
}


</script>

<style scoped>
.questions-view {
  height: 100vh;
  background: linear-gradient(180deg, #E2E8F0 0%, #F8FAFC 100%);
  font-family: 'Inter', sans-serif;
  overflow: hidden;
}

.questions-container {
  display: flex;
  min-height: calc(100vh - 64px); /* 减去NavBar的高度64px */
  overflow: hidden;
}

/* 侧边栏样式 */
.sidebar {
  width: 280px;
  background: #F8F9FA;
  border-right: 1px solid #E5E7EB;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
}

.sidebar.collapsed {
  width: 0;
  overflow: hidden;
}

.sidebar-header {
  padding: 24px;
  border-bottom: 1px solid #E5E7EB;
}

.title {
  font-size: 20px;
  font-weight: 600;
  color: #1F2937;
  margin: 0 0 8px 0;
}

.subtitle {
  font-size: 14px;
  color: #6B7280;
  margin: 0;
}

.nav-menu {
  padding: 16px;
}

.nav-item {
  width: 100%;
  height: 45px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 700;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.nav-item.active {
  background: #000;
  color: white;
}

.nav-item:not(.active) {
  background: white;
  color: #6B7280;
  border: 1px solid #D9D9D9;
}

.nav-item:not(.active):hover {
  background: #F3F4F6;
}

.selected-stats {
  flex: 0.96;
  display: flex;
  align-items: end;
  padding: 16px;
  border-top: 1px solid #E5E7EB;
}

.stats-card {
  width: 100%;
  background: #E6F1FF;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
}

.stats-card h3 {
  font-size: 20px;
  font-weight: 500;
  color: #1E40AF;
  margin: 0 0 20px 0;
}

.count {
  font-size: 32px;
  font-weight: 700;
  color: #1E40AF;
}

/* 主内容区样式 */
.main-content {
  flex: 1;
  padding: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.top-bar {
  background: white;
  border-bottom: 1px solid #E5E7EB;
  padding: 25px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.top-bar h2 {
  font-size: 24px;
  font-weight: 600;
  color: #1F2937;
  margin: 0;
}

.generate-btn {
  background: #F3F4F6;
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-size: 15px;
  font-weight: 500;
  color: #9CA3AF;
  cursor: pointer;
  transition: all 0.2s;
}

.generate-btn:not(:disabled) {
  background: #1F2937;
  color: white;
}

.generate-btn:not(:disabled):hover {
  background: #374151;
}

.filter-bar {
  padding: 20px 24px;
  display: flex;
  align-items: center;
  gap: 20px;
  background: white;
  border-bottom: 1px solid #E5E7EB;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  white-space: nowrap;
}

.search-group {
  flex: 1;
  max-width: 300px;
}

/* 题目列表样式 */
.questions-list {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-height: calc(100vh - 64px - 72px - 70px); /* NavBar + TopBar + filter-bar 的大概高度 */
}

.question-card {
  background: white;
  border: 1px solid #E5E7EB;
  border-radius: 12px;
  padding: 24px;
  transition: all 0.2s;
}

.question-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.question-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.type-tag, .difficulty-tag {
  padding: 4px 12px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
}

.question-content {
  margin-top: 16px;
}

.question-text {
  font-size: 16px;
  color: #1F2937;
  margin: 0 0 16px 0;
  line-height: 1.5;
}

.options {
  margin: 16px 0;
}

.option {
  font-size: 14px;
  color: #6B7280;
  margin: 8px 0;
  line-height: 1.5;
}

.answer {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #F3F4F6;
}

.answer-label {
  font-size: 14px;
  color: #059669;
  font-weight: 500;
}

.answer-text {
  font-size: 14px;
  color: #059669;
}

.type-choice {
  background: #EFF6FF;
  color: #1E40AF;
}

.type-fill {
  background: #F0FDF4;
  color: #166534;
}

.type-essay {
  background: #FEF3C7;
  color: #92400E;
}

.difficulty-easy {
  background: #DCFCE7;
  color: #166534;
}

.difficulty-medium {
  background: #FEF3C7;
  color: #92400E;
}

.difficulty-hard {
  background: #FEE2E2;
  color: #DC2626;
}

/* Element Plus 样式覆盖 */
:deep(.el-select) {
  width: 120px;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-button) {
  height: 38px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .questions-container {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    height: auto;
    border-right: none;
    border-bottom: 1px solid #E5E7EB;
  }
  
  .sidebar.collapsed {
    height: 0;
    width: 100%;
  }
  
  .filter-bar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .filter-group {
    justify-content: space-between;
  }
}

</style>
